package com.example.demo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.util.HttpClientUtil;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 * @Author yuzw
 * @DATE 2018/4/4.
 */
@Controller
public class WechatController {
    private static String TOKEN = "bdshop";
    private String echostr;
    @RequestMapping("/bdshop")
    public void test(HttpServletRequest request, HttpServletResponse response){
        try {
            System.out.println("success");
            connect(request,response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    @RequestMapping("/authorize")
    @ResponseBody
    public String authorize(HttpServletRequest request, HttpServletResponse response){
        String authorizeUrl  = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx3cd777a6841eafe6&redirect_uri=http%3a%2f%2fbdshop.free.ngrok.cc&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
        return authorizeUrl;

    }

    @RequestMapping("/")
    public void index(HttpServletRequest request, HttpServletResponse response){
        String code = request.getParameter("code");
        String access_token_url  = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx3cd777a6841eafe6&secret=dd75fd6954df4bdb52112a4cc68cf55d&code="+code+"&grant_type=authorization_code";
        String json = HttpClientUtil.doGet(access_token_url);
        JSONObject jsonObj = JSON.parseObject(json);
        String openid = (String) jsonObj.get("openid");
        String access_token = (String) jsonObj.get("access_token");
        String getinfo = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid;
        String baseInfo = HttpClientUtil.doGet(getinfo);
        JSONObject baseinfoObj = JSON.parseObject(baseInfo);
        System.out.println(baseinfoObj.toJSONString());
    }
    /**
     *@author haibing.xiao
     *@return
     *@exception
     *@param
     *
     * <p>接入连接生效验证</p>
     */
    private void connect(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
        if(!accessing(request, response)){
            return ;
        }
        String echostr=getEchostr();
        if(echostr!=null && !"".equals(echostr)){
            response.getWriter().print(echostr);
        }
    }
    /**
     * @author haibing.xiao
     * Date 2013-05-29
     * @return boolean
     * @exception ServletException, IOException
     * @param
     *
     *<p>用来接收微信公众平台的验证</p>
     */
    private boolean accessing(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        if(StringUtils.isEmpty(signature)){
            return false;
        }
        if(StringUtils.isEmpty(timestamp)){
            return false;
        }
        if(StringUtils.isEmpty(nonce)){
            return false;
        }
        if(StringUtils.isEmpty(echostr)){
            return false;
        }
        String[] ArrTmp = { TOKEN, timestamp, nonce };
        Arrays.sort(ArrTmp);
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < ArrTmp.length; i++) {
            sb.append(ArrTmp[i]);
        }
        String pwd = Encrypt(sb.toString());

        if(pwd.trim().equals(signature.trim())){
            this.echostr =echostr;
            return true;
        }else{
            return false;
        }
    }
    private String Encrypt(String strSrc) {
        MessageDigest md = null;
        String strDes = null;

        byte[] bt = strSrc.getBytes();
        try {
            md = MessageDigest.getInstance("SHA-1");
            md.update(bt);
            strDes = bytes2Hex(md.digest());
        } catch (NoSuchAlgorithmException e) {
            System.out.println("Invalid algorithm.");
            return null;
        }
        return strDes;
    }

    public String bytes2Hex(byte[] bts) {
        String des = "";
        String tmp = null;
        for (int i = 0; i < bts.length; i++) {
            tmp = (Integer.toHexString(bts[i] & 0xFF));
            if (tmp.length() == 1) {
                des += "0";
            }
            des += tmp;
        }
        return des;
    }


    public String getEchostr(){
        return echostr;
    }
}
